import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:get/get.dart';
import 'package:openim_common/openim_common.dart';

import '../../../../routes/app_navigator.dart';
import '../../../chat/chat_logic.dart';
import '../../../conversation/conversation_logic.dart';
import '../../select_contacts/select_contacts_logic.dart';
import '../user_profile _panel_logic.dart';

class FriendSetupLogic extends GetxController {
  final conversationLogic = Get.find<ConversationLogic>();
  final userProfilesLogic = Get.find<UserProfilePanelLogic>(tag: GetTags.userProfile);
  late String userID;

  @override
  void onInit() {
    userID = Get.arguments['userID'];
    super.onInit();
  }

  void toggleBlacklist() {
    if (userProfilesLogic.userInfo.value.isBlacklist == true) {
      removeBlacklist();
    } else {
      addBlacklist();
    }
  }

  void addBlacklist() async {
    var confirm = await Get.dialog(CustomDialog(title: StrRes.areYouSureAddBlacklist));
    if (confirm == true) {
      await OpenIM.iMManager.friendshipManager.addBlacklist(
        userID: userProfilesLogic.userInfo.value.userID!,
      );
      userProfilesLogic.userInfo.update((val) {
        val?.isBlacklist = true;
      });
    }
  }

  void removeBlacklist() async {
    await OpenIM.iMManager.friendshipManager.removeBlacklist(
      userID: userProfilesLogic.userInfo.value.userID!,
    );
    userProfilesLogic.userInfo.update((val) {
      val?.isBlacklist = false;
    });
  }

  void deleteFromFriendList() async {
    var confirm = await Get.dialog(CustomDialog(
      title: StrRes.areYouSureDelFriend,
      rightText: StrRes.delete,
    ));
    if (confirm) {
      await LoadingView.singleton.wrap(asyncFunction: () async {
        await OpenIM.iMManager.friendshipManager.deleteFriend(
          userID: userProfilesLogic.userInfo.value.userID!,
        );
        userProfilesLogic.userInfo.update((val) {
          val?.isFriendship = false;
        });

        final userIDList = [
          userProfilesLogic.userInfo.value.userID,
          OpenIM.iMManager.userID,
        ];
        userIDList.sort();
        final conversationID = 'si_${userIDList.join('_')}';

        await OpenIM.iMManager.conversationManager.deleteConversationAndDeleteAllMsg(conversationID: conversationID);

        conversationLogic.list.removeWhere((e) => e.conversationID == conversationID);
        conversationLogic.update();
      });

      if (userProfilesLogic.offAllWhenDelFriend == true) {
        AppNavigator.startBackMain();
      } else {
        Get.back();
      }
    }
  }
  
    // 优先从好友信息、用户缓存、后端接口顺序获取最新头像URL
  Future<String?> _resolveFaceURL(String userID) async {
        try {
            final friendInfo = (await OpenIM.iMManager.friendshipManager.getFriendsInfo(
              userIDList: [userID],
            )).firstOrNull;
            final url = friendInfo?.faceURL;
            if (IMUtils.isUrlValid(url)) return url!;
        } catch (_) {}

        try {
            final userInfo = (await OpenIM.iMManager.userManager.getUsersInfoWithCache([userID])).firstOrNull;
            final url = userInfo?.faceURL;
            if (IMUtils.isUrlValid(url)) return url!;
        } catch (_) {}

        try {
            final list = await Apis.getUserFullInfo(userIDList: [userID]);
            final info = list?.firstOrNull;
            final url = info?.faceURL;
            if (IMUtils.isUrlValid(url)) return url!;
        } catch (_) {}

        return null;
  }

      recommendToFriend() async {
        // 目标用户ID
        final targetUserID = userProfilesLogic.userInfo.value.userID!;
        // 基础名片信息（来自用户资料面板）
        final baseCardMap = userProfilesLogic.userInfo.value.toJson();
        String? latestFaceURL = baseCardMap['faceURL'] as String?;

        // 如果现有头像URL无效，则刷新获取
        if (!IMUtils.isUrlValid(latestFaceURL)) {
            latestFaceURL = await _resolveFaceURL(targetUserID);
        }
        // 将有效的最新头像URL写入名片信息
        if (IMUtils.isUrlValid(latestFaceURL)) {
            baseCardMap['faceURL'] = latestFaceURL;
        } else {
            // 保持为null，避免传递空字符串
            baseCardMap.remove('faceURL');
        }
        final cardUserInfo = UserInfo.fromJson(baseCardMap);

        final isRegistered = Get.isRegistered<ChatLogic>(tag: GetTags.chat);
        if (isRegistered) {
            // 直接将刷新后的名片信息传给聊天逻辑
            final logic = Get.find<ChatLogic>(tag: GetTags.chat);
            logic.recommendFriendCarte(cardUserInfo);
            return;
        }

        // 进入选择联系人页面，名片信息包含最新的头像URL
        final result = await AppNavigator.startSelectContacts(
          action: SelAction.recommend,
          ex: '[${StrRes.carte}]${userProfilesLogic.userInfo.value.nickname}',
          cardUserInfo: cardUserInfo,
        );

        if (null != result) {
            final customEx = result['customEx'];
            final checkedList = result['checkedList'];
            for (var info in checkedList) {
                final userID = IMUtils.convertCheckedToUserID(info);
                final groupID = IMUtils.convertCheckedToGroupID(info);

                if (customEx is String && customEx.isNotEmpty) {
                    OpenIM.iMManager.messageManager.sendMessage(
                      message: await OpenIM.iMManager.messageManager.createTextMessage(text: customEx),
                      userID: userID,
                      groupID: groupID,
                      offlinePushInfo: Config.offlinePushInfo,
                    );
                }

                // 使用刷新后的头像URL构造名片消息
                OpenIM.iMManager.messageManager.sendMessage(
                  message: await OpenIM.iMManager.messageManager.createCardMessage(
                    userID: targetUserID,
                    nickname: userProfilesLogic.userInfo.value.showName,
                    faceURL: cardUserInfo.faceURL, // 最新头像URL（可能为null，SDK允许）
                  ),
                  userID: userID,
                  groupID: groupID,
                  offlinePushInfo: Config.offlinePushInfo,
                );
            }
        }
  }
  
  void setFriendRemark() => AppNavigator.startSetFriendRemark();
}
